// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`
// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`
const request = require('./src/utils/request')
const githubUsername = 'XIET08'

const apiList = [
  {
    name: 'Project',
    url: `/users/${githubUsername}/repos`
  },
  {
    name: 'Follower',
    url: `/users/${githubUsername}/followers`
  },
  {
    name: 'Following',
    url: `/users/${githubUsername}/following`
  },
  {
    name: 'Gist',
    url: `/users/${githubUsername}/gists`,
    processData: async (blogs) => {
      let result = []
      for (let i = 0; i < blogs.length; i++) {
        const item = blogs[i]
        let blog = {}
        const { data } = await request(`/gists/${item.id}`)
        for (let key in data.files) {
          blog['title'] = key
          blog['content'] = data.files[key]['content']
          blog['url'] = data.files[key]
          blog['id'] = item.id
          blog['description'] = data['description']
          blog['createTime'] = data['created_at']
          blog['updateTime'] = data['updated_at']
          blog['hide'] = false
          break
        }
        result.push(blog)
      }
      return result
    }
  }
]

module.exports = function (api) {
  api.loadSource(async ({ addCollection }) => {
    // Use the Data Store API here: https://gridsome.org/docs/data-store-api/

    for (let i = 0; i < apiList.length; i++) {
      const api = apiList[i]
      const collection = addCollection(api.name)
      let { data } = await request({
        method: 'GET',
        url: api.url
      })

      if (api.processData) {
        data = await api.processData(data)
      }

      for (const item of data) {
        collection.addNode({
          ...item
        })
      }
    }

  })

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  })
}
